import base64
import urllib2
import json
import InitConfig as config
import log_file
import os

a = config.Config()
ip = a.getWebIP()
port = a.getWebPort()
registAction = a.getRegistAction()
import_action = a.getImportMsgAction()
webProject = a.getWebProJectName()
log_path = a.getLogPath()
cobbler_ip = a.getCobblerIp()
cobbler_port =a.getCobblerPort()
ks_path = a.getKsPath()
ks_file = a.getKsTemplateFile()
# LAST_CONTENT_SIZE = 0
lastSystem = []


def registerCobblerToWeb(cobbled_status):
    """
    register to web project
    :return:
    """
    synToJavaUrl = "http://%s:%s/%s/%s/{%s}/{%s}" % (ip, port, webProject, registAction,cobbler_ip,cobbler_port)
    #synToJavaUrl="http://192.168.1.107:8080/csa/V/1/server/1/%s/8061"%(cobbler_ip)
    values = {"type": "regist", "cobbler": "%s" % (str(cobbled_status)),'ip':'%s'%(cobbler_ip),'port':"8061"}
    jdata = json.dumps(values)
    sendType = True
    try:
        req = urllib2.Request(url=synToJavaUrl, headers={'Content-type': 'text/json'})
        req.add_data(jdata)
        rep = urllib2.urlopen(req)
        sendType = True
    except:
        sendType = False
    finally:
        log_file.writeTextLog("regist", ip=ip, port=port, cobbled_status=cobbled_status, sendType=sendType)


def importStatus(taskId,osName, imp_type, content=""):
    """
    send to web project with import message
    :param content:  other content , default is ""
    :param osName:  importName take by web project
    :param imp_type:  import sattus
    :return:
    """
    synToJavaUrl = "http://%s:%s/%s/%s/{%s}/{status:%s}/{isEnd:%s}" % (ip, port, webProject, import_action,taskId,imp_type,imp_type)
    values = {"type": "import_message", "content": "%s" % (content), "url": "%s" % (cobbler_ip),
              "OSName": "%s" % (osName),
              "importType": "%s" % (imp_type)}
    jdata = json.dumps(values)
    sendType = True
    try:
        req = urllib2.Request(url=synToJavaUrl, headers={'Content-type': 'text/json'})
        req.add_data(jdata)
        rep = urllib2.urlopen(req)
        sendType = True
    except:
        sendType = False
    finally:
        log_file.writeTextLog("import", "cobbler send to web project", sendType)

def downloadStatus(taskId,osName, down_type, content=""):
    '''
    return download result
    :param taskId:
    :param osName:
    :param down_type:
    :param content:
    :return:
    '''
    synToJavaUrl = "http://%s:%s/%s/%s/{%s}/{status:%s}/{isEnd:%s}" % (ip, port, webProject, import_action,taskId,down_type,down_type)
    values = {"type": "import_message", "content": "%s" % (content), "url": "%s" % (cobbler_ip),
              "OSName": "%s" % (osName),
              "importType": "%s" % (down_type),"errorMsg":"%s"%(content)}
    jdata = json.dumps(values)
    sendType = True
    try:
        req = urllib2.Request(url=synToJavaUrl, headers={'Content-type': 'text/json'})
        req.add_data(jdata)
        rep = urllib2.urlopen(req)
        sendType = True
    except:
        sendType = False
    finally:
        log_file.writeTextLog("import", "cobbler send to web project", sendType)

def sendJAVADataPost(sys_name, file, size, offset, data):
    """
    send install message to web Project
    :param sys_name:   system name
    :param file:  log file name
    :param size:  content size
    :param offset: area
    :param data:   content
    :return:
    """
    if offset != -1:
        if size is not None:
            if size != len(data):
                return True
    fileName = file.split(".")[0]
    if fileName == "anaconda":
        if data is not "":

            index = __addList(sys_name, fileName, size)
            contents = data[index:]
            if "moving (1) to step autopartitionexecute" in contents:
                contents = "starting fen qu ...."
                __send_install_message(contents, index, size, data)
                # if "leaving (1) step autopartitionexecute" in contents:
                #     contents = "fen qu ending ..."
                #     __send_install_message(contents, index, size, data)
                # if "moving (1) to step preinstallconfig" in contents:
                # contents = "an zhuang qian de jia zai pei zhi  .... "
                # __send_install_message("an zhuang qian de jia zai pei zhi  .... ", index, size, data)
            # if "leaving (1) step preinstallconfig" in contents:
            #     contents = "bei zhi wan cheng ..."
            #     __send_install_message(contents, index, size, data)
            # if "moving (1) to step installpackages" in contents:
            #     contents = "begin install package..."
            #     __send_install_message(contents, index, size, data)
            if "moving (1) to step installpackages" in contents:
                contents = "begin install package..."
                __send_install_message(contents, index, size, data)
            if "leaving (1) step installpackages" in contents:
                contents = "install package ending..."
                __send_install_message(contents, index, size, data)
            if "moving (1) to step postinstallconfig" in contents:
                contents = "begin an zhaung hou de pei zhi ...."
                __send_install_message(contents, index, size, data)
            if "leaving (1) step postinstallconfig" in contents:
                contents = "an zhaung hou de pei zhi wan cheng ..."
                __send_install_message(contents, index, size, data)
            if "setting SELinux contexts for anaconda created files" in data:
                contents = "will reboot ..."
                __send_install_message(contents, index, size, data)

    # if fileName == "install":
    #     if data is not "":
    #         index = __addList(sys_name, fileName, size)
    #         contents = data[index:]
    #         if contents is not "":
    #             __send_install_message(contents, index, size, data)

    return True


def __send_install_message(contents, index, size, data):
    synToJavaUrl = "http://%s:%s/%s/%s?account=guopengfei&receiver=0001" % (
        ip, port, webProject, action)  # contents = data
    values = {'type': 'install-message', 'content': contents, "index": "%s---%s" % (index, size)}
    jdata = json.dumps(values)

    try:
        req = urllib2.Request(url=synToJavaUrl, headers={'Content-type': 'text/json'})
        req.add_data(jdata)
        urllib2.urlopen(req)
        sendType = 1
    except:
        sendType = 0
    finally:
        writeTextLog(synToJavaUrl, data, sendType)


def __addList(systemName, file, size):
    """
    cache the install data
    :param systemName: systemName
    :param size:  content size
    :return:
    """
    for h in range(len(lastSystem)):
        try:
            tempSysName = lastSystem[h]["system-%s" % (file)]
            if tempSysName == systemName:
                temp = lastSystem[h]["lastSize"]
                lastSystem[h]["lastSize"] = size
                return temp
        except:
            continue
    sys = {}
    sys["system-%s" % (file)] = systemName
    sys["lastSize"] = size
    lastSystem.append(sys)
    # print len(MSD_DSFSDF)
    return 0


def writeTextLog(synToJavaUrl, content, sendType):
    try:
        file = log_path
        f = open(file, 'a')
        if sendType == 1 or sendType == "1":
            f.write("send to %s  success!\n " % (synToJavaUrl))
        else:
            f.write("send to %s error!\n " % (synToJavaUrl))
            # f.write("http://%s:%s/%s/%s?account=guopengfei&receiver=0001"%(ip,port,webProject,action))
    finally:
        f.close()

